// CTL
 

function Controller(pageBlockerID, messageBoxID, messageContent, stateRecButton){

	this.pageBlockerID = pageBlockerID;
	this.messageBoxID = messageBoxID;
	this.messageContentID = messageContent;
	this.taxaList = new Array();
	this.taxaCount = 0;
	this.currTaxa = 'All';
	this.stateList = new Array(); 
	this.stateCount = 0;
	this.currState = 'All';
	this.speciesList = new Array();
	this.baseQueryURL = '/query?';
	this.swapDataFile = '/data?type=json&json_file=default'; 
	this.state2taxaFile = '/data?type=json&json_file=state2taxa';
	this.taxa2stateFile = '/data?type=json&json_file=taxa2state';
	this.spjsonFile = '/spinfo?source=profile&sname=';
	
	// OBSOLETE Data Files
	//this.swapDataFile = '/data/json/swap_default.json'; 
	//this.state2taxaFile = '/data/json/swap_state2taxa.json';
	//this.taxa2stateFile = '/data/json/swap_taxa2state.json';	
	//this.missingSpeciesFile = '/data/json/recommended_swap_species.json'; 
	
	this.stateRecommendationButton = stateRecButton;
}

Controller.prototype.PrintMessage = function (text){
	$('#' + this.messageContentID).html(text);
	$('#' + this.messageBoxID).show();
}

Controller.prototype.CloseInformationPanel = function(){
	$('#' + this.messageBoxID).hide();
}
Controller.prototype.LoadPage = function(){

	pchart.DrawBlankPieChart();
	map.DrawBlankGeoMap();

	this.LoadDefaultData();
	var data = this.GetFormattedDataTable(this.taxaCount, this.taxaList, 'Taxa', 'GCN Species');
	pchart.DrawPieChart(data);
	data = this.GetFormattedDataTable(this.stateCount, this.stateList, 'State', 'GCN Species');
	map.DrawGeoMap(data);
	
	
	this.LoadGeoMapData();
	this.LoadPieChartData();
	//this.LoadMissingSpeciesData();
	
	$('#' + this.pageBlockerID).hide();
}

Controller.prototype.ReloadPage = function(){
	this.ReloadPieChart();
	this.ReloadGeoMap();
	map.RestoreGeoMap();
	map.MinimizeList();
	pchart.RestorePieChart();
	pchart.MinimizeList();
	this.currTaxa = 'All';
	this.currState = 'All';
}

Controller.prototype.ReloadPieChart = function(){
	for(var taxa in defaultData.taxa){
			 
				ctl.taxaList[taxa] = defaultData.taxa[taxa];
				ctl.taxaCount++;
	}
	var data = this.GetFormattedDataTable(this.taxaCount, this.taxaList, 'Taxa', 'GCN Species');
	pchart.DrawPieChart(data);
	$('#' + pchart.pchartHeaderID).html('Species by Taxa');
	
}

Controller.prototype.ReloadGeoMap = function(){
	for(var state in defaultData.state){
				ctl.stateList[state] = defaultData.state[state];
				ctl.stateCount++;
	}
	var data = this.GetFormattedDataTable(this.stateCount, this.stateList, 'State', 'GCN Species');
	map.DrawGeoMap(data);
	$('#' + map.mapHeaderID).html('Species by State');
	
}

Controller.prototype.GetFormattedDataTable = function(count, list, col1Label, col2Label){

	var data = new google.visualization.DataTable();
	    
	data.addColumn('string', col1Label);
	data.addColumn('number', col2Label);
	
	var item = '';
	var speciesCount = 0;

	//data.addRows(count); 
	var i = 0;
	for(var item in list){
	    if(col1Label == 'State' && i > 49) { break; }
			var speciesCount = list[item];
			data.addRow([item, speciesCount]);
			//data.setValue(i,0,item);
			//data.setValue(i,1, speciesCount);
			
			i++;
	
	}
 
	return data;
}

Controller.prototype.LoadMissingSpeciesData = function(){

	var _url = this.missingSpeciesFile;

 
	$.ajax({
		dataType: "json",
		url: _url,
		async: false,
		ifModified: true,
		success: function(string) {
			//data = $.parseJSON(string);
		 
			missingSpecies = string;
			 
		},
		error: function(msg){
			alert(msg);
		}
	});

  
 
}

Controller.prototype.LoadDefaultData = function(){

	var _url = this.swapDataFile;


	$.ajax({
		dataType: "json",
		url: _url,
		async: false,
		ifModified: true,
		success: function(string) {
			//data = $.parseJSON(string);
			 
			defaultData = string;
			 
		},
		failure: function(msg){
			alert(msg);
		}
	});

	for(var state in defaultData.state){
				ctl.stateList[state] = defaultData.state[state];
				ctl.stateCount++;
	}
	for(var taxa in defaultData.taxa){
			 
				ctl.taxaList[taxa] = defaultData.taxa[taxa];
				ctl.taxaCount++;
	}
 
}

Controller.prototype.LoadGeoMapData = function(){

    var _url = this.taxa2stateFile;

	$.ajax({
		dataType: "json",
		url: _url,
		async: false,
		ifModified: true,
		success: function(string) {
	
			mapData = string;
		
		},
		failure: function(msg){
			alert(msg);
		}
	});


}

Controller.prototype.LoadPieChartData = function(){

    var _url = this.state2taxaFile;

	$.ajax({
		dataType: "json",
		url: _url,
		async: false,
		ifModified: true,
		success: function(string) {
			pchartData = string;
	 
		},
		failure: function(msg){
			alert(msg);
		}
	});


}

Controller.prototype.LoadPieChartDataForState = function(state){

	var list = pchartData[state];
	var totalSpecies = 0;
	var spList = new Array();
	this.taxaCount = 0;

	for(var taxa in list){	
		this.taxaList[taxa] =  list[taxa].count;
		this.taxaCount++;
		if(list[taxa].count > 0){
			var templist = list[taxa].list;
			for(var key in templist){	
	
					var sciName = templist[key].value[0];
					var commonName = templist[key].value[1];
					if(spList[sciName] == undefined){
						spList[sciName] = commonName;
						totalSpecies++;
					} 
					
			}
		}		
	}
	
	var data = this.GetFormattedDataTable(this.taxaCount, this.taxaList, 'Taxa', 'GCN Species');
	pchart.DrawPieChart(data); 
	splist.PrintSpeciesList(spList, totalSpecies, pchart.listBoxID);
	/*
	 * OBSOLETE: No longer providing missing species recommendation/analysis
	var htmlText = '';
	
	for(var st in missingSpecies){
	
		if(st == state){

			htmlText = '&middot; Additional Species to Consider for ' + state;
			
			break;
		}
	}
	
 
	$('#' + this.stateRecommendationButton).html(htmlText); 
	*/
	spList = null;
	
}

Controller.prototype.LoadGeoMapDataForTaxa = function(taxa){

	var list = mapData[taxa];
	var totalSpecies = 0;
	var spList = new Array();
	this.stateCount = 0;
 
	for(var state in list){	
		// not drawing the territories
		if(this.stateCount < 50){
			this.stateList[state] =  list[state].count; 
			this.stateCount++;
		}
		//this.stateCount++;
		if(list[state].count > 0){
			var templist = list[state].list;
			for(var index in templist){		 
					var sciName = templist[index].value[0];	
					var commonName = templist[index].value[1];					
					if(spList[sciName] == undefined){
						spList[sciName] = commonName;
						totalSpecies++;
					} 		 
			}
		}
	}

	var data = this.GetFormattedDataTable(this.stateCount, this.stateList, 'State', 'GCN Species');
	 
	map.DrawGeoMap(data); 
	splist.PrintSpeciesList(spList, totalSpecies, map.listBoxID);
	spList = null;
}

Controller.prototype.PrintFilteredSpeciesList = function(data, top, item, elemID){

	var totalSpecies = 0;
	var spList = new Array();
	var list = data[top][item].list;
 
	for(var index in list){		 
					var sciName = list[index].value[0];	
					var commonName = list[index].value[1];
					if(spList[sciName] == undefined){
						spList[sciName] = commonName;
						totalSpecies++;
					} 		 
	}
	splist.PrintSpeciesList(spList, totalSpecies, elemID);
	spList = null;
}
 
Controller.prototype.LoadSpeciesInformation = function(sName){

    var _url = this.spjsonFile + escape(sName);
	var species = new Species(sName, 'n/a', new Array());
	 
	
	$.ajax({
		dataType: "json",
		url: _url,
		async: false,
		ifModified: true,
		success: function(string) {
			data = string;
			var vname = '';
			for(var vn in data.vernacularNames){
				vname += data.vernacularNames[vn] + ", ";
			}
			vname = vname.replace(/,\s/,''); 
			species.vernacularName = vname;
			var i = 0;
			for(var state in data.states){
			
				species.stateList[i++] = data.states[state];
			
			}	 	
		},
		failure: function(msg){
			alert(msg);
		}
	});
 
	return species;
}

Controller.prototype.ShowGeoMapView = function(view){

	 
	var data = this.GetFormattedDataTable(this.stateCount, this.stateList, 'State', 'GCN Species');

	var elemID = map.mapID;
	if(view == 'default'){
		map.DrawGeoMap(data); 
	}
	else {
		
		this.ShowAlternateView(data, elemID, view);
	}
	 
}

Controller.prototype.ShowPieChartView = function(view){

	 
	var data = this.GetFormattedDataTable(this.taxaCount, this.taxaList, 'Taxa', 'GCN Species');

	var elemID = pchart.pchartID;
	if(view == 'default'){
		pchart.DrawPieChart(data); 
	}
	else {
		this.ShowAlternateView(data, elemID, view);
	}
}

Controller.prototype.ShowAlternateView = function(data, elemID, view){
	
	if(view == 'table'){
			var table = new google.visualization.Table(document.getElementById(elemID));
			var options = {};
			options['sortColumn'] = 1;
			options['width'] = 420;
			options['page'] = 'enable';
			options['pageSize'] = 15;
			options['pagingSymbols'] = {prev: 'prev', next: 'next'};
			options['pagingButtonsConfiguration'] = 'auto';
			table.draw(data, options);
	}
	else if(view == 'barchart'){
		
		    var barchart = new google.visualization.BarChart(document.getElementById(elemID));
			var options = {};
			options['is3D'] = true;
			options['width'] = 420;
			options['backgroundColor'] ='#e9f7f9';
			barchart.draw(data, options);
	}
	 
}


/*------- event handlers --------*/
function piechart_mouseover(text){
	
	 
	if($('#piechartLabelDiv') != null){
		$('#piechartLabelDiv').remove();
	}		
	var newTaxaLabelDiv = $('<div></div>');
	newTaxaLabelDiv.attr('id','piechartLabelDiv');
	newTaxaLabelDiv.empty();
	if(ctl.currState != 'All'){
		text = ctl.currState + ': ' + text;
	}
	newTaxaLabelDiv.html(text);
	newTaxaLabelDiv.appendTo('#' + pchart.pchartID );
	$('#piechartLabelDiv').attr('class', 'pieChartTooltip');	
	
}

function piechart_mouseout(){

	var oldChild = $('#piechartLabelDiv');
	if(oldChild != null){
		$('#piechartLabelDiv').remove();
	}	
				
}

function piechart_onclick(taxa){

 
	if($('#' + map.panelID).css('display') != 'none'){
	    // need to put in code for not redrawing chart when removing filter
		if(ctl.currState == 'All'){
			pchart.MinimizePieChart();
			ctl.LoadGeoMapDataForTaxa(taxa);	
			$('#' + map.listPanelID).css('display', 'block');
			$('#' + map.mapHeaderID).html('Species by State for ' + taxa + '<span onclick="ctl.ReloadPage();"> <span style=\"color:#0060c9;cursor:pointer;\">[Restore Default View]</span></span>'); 
			$('#' + map.listHeaderID).html('');
			ctl.currTaxa = taxa;
		}
		else {
			var text = 'In order to redraw the map for a taxon, <span style=\"color:#0060c9;cursor:pointer;\" onclick="ctl.ReloadPage();">restore default view</span>. To filter species lists by a specific taxon for state ' + ctl.currState;
			text += ', please <span style=\"color:#0060c9;cursor:pointer;\" onclick="map.MinimizeGeoMap();">minimize</span> the map first.';
			ctl.PrintMessage(text);
 
		}
		
	}
	else {
		ctl.PrintFilteredSpeciesList(pchartData, ctl.currState, taxa, pchart.listBoxID);

		$('#' + pchart.listHeaderID).html('Filtered by: ' + taxa + '<span onclick="geomap_onclick(\'' + ctl.currState + '\');"> <span style=\"color:#0060c9;cursor:pointer;\">[remove filter]</span></span>');
	}	
}

function geomap_onclick(state){

	// Click on map where both panels are open ==> close map panel and open taxa panel
	if($('#' + pchart.panelID).css('display') != 'none'){
		if(ctl.currTaxa == 'All'){
			map.MinimizeGeoMap();
			ctl.LoadPieChartDataForState(state);
			$('#' + pchart.listPanelID).css('display', 'block');
			$('#' + pchart.pchartHeaderID).html('Species by Taxon for ' + state + '<span onclick="ctl.ReloadPage();"> <span style=\"color:#0060c9;cursor:pointer;\">[Restore Default View]</span></span> <a href="/download?state=' + state + '" target="_blank" style="background:#6b9dff;padding:4px;color:#eeeeee;text-decoration:none;">Downloadable Data</a>');
			ctl.currState = state;
			$('#' + pchart.listHeaderID).html('');
			
		}
		else {
			var text = 'In order to draw a taxa chart for a state, <span onclick="ctl.ReloadPage();" style=\"color:#0060c9;cursor:pointer;\">restore default view</span>. To filter species lists by a specific state for taxon ' + ctl.currTaxa;
			text += ', please  <span style=\"color:#0060c9;cursor:pointer;\" onclick="pchart.MinimizePieChart();">minimize</span> the pie chart first.';
			ctl.PrintMessage(text);
 
		}
	}
	// if only taxa panel is open, then filter species list
	else {
		ctl.PrintFilteredSpeciesList(mapData, ctl.currTaxa, state, map.listBoxID);
		$('#' + map.listHeaderID).html('Filtered by: ' + state + '<span onclick="piechart_onclick(\'' + ctl.currTaxa + '\');"> <span style=\"color:#0060c9;cursor:pointer;\">[remove filter]</span></span>');
		
	}	
	
}

function missing_species_onclick(sName, state){

	$('#' + ctl.pageBlockerID).css('display','');
	$('#' + ctl.messageBoxID).css('display','');
	
	var species = ctl.LoadSpeciesInformation(sName);
	
	splist.ShowSpeciesInformation(species); 	
	$('#missingSpeciesState').html('Potential missing state: ' +  state);
	$('#' + ctl.pageBlockerID).css('display','none');
	$('#' + ctl.messageBoxID).css('display','none');
}

function speciesname_onclick(sName){

	$('#' + ctl.pageBlockerID).css('display','');
	$('#' + ctl.messageBoxID).css('display','');
	
	var species = ctl.LoadSpeciesInformation(sName);
	
	splist.ShowSpeciesInformation(species); 	
	$('#missingSpeciesState').html('');
	$('#' + ctl.pageBlockerID).css('display','none');
	$('#' + ctl.messageBoxID).css('display','none');
}

function species_search_onclick(sName){

	if(sName == ''){
		return false;
	}
	//splist.CloseSpeciesSearchResultPanel();			
	
	speciesname_onclick(sName);
}

 function extract_state(stateAbbr){
 
    if(!stateAbbr.match(/US-/)){
	 
		return stateAbbr;
	}
    var state = stateAbbr.replace(/US-/,'');
	
    state = stateAbbrIndex[state];
	return state;
 }
 
 function valid_taxa(taxa){
	 
	 if(taxa == null ) return false;
	 
	 taxa = taxa.toLowerCase();
	 
	 for (var taxaKey in taxaIndex) {
		 
		 if(taxaKey.toLowerCase() == taxa){
			 return true;
		 }
	 	 
	 }
 
	 return false;
	 
 }
 
 function valid_state(state){
	 
	 if(state == null ) return false;
	 
	 state = state.toLowerCase();
	 
	 for (var stateAbbr in stateAbbrIndex) {
		 
		 if(stateAbbrIndex[stateAbbr].toLowerCase() == state){
			 return true;
		 }
	 	 
	 }
 
	 return false;
	 
 }